package cs.fsu.fsview;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

import org.htmlcleaner.HtmlCleaner;
import org.htmlcleaner.TagNode;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

public class StoryActivity extends Activity {

	TextView title, subtitle, byline, article;

	private static final String TAG = "cs.fsu.fsuview.StoryActivity";

	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);

		setContentView(R.layout.story);

		title = (TextView) findViewById(R.id.txtTitle);
		subtitle = (TextView) findViewById(R.id.txtSubtitle);
		byline = (TextView) findViewById(R.id.txtByline);
		article = (TextView) findViewById(R.id.txtArticle);
	}

	public void onResume(){
		super.onResume();

		String link = getIntent().getStringExtra("link");

		URL source;
		TagNode node = null;
		HtmlCleaner cleaner = new HtmlCleaner();

		Log.i(TAG, "Open Story link " + link);

		try {
			source = new URL(link);
			node = cleaner.clean(source, "UTF-8");
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		Log.i(TAG, node.getText() + "");

		TagNode header = node.findElementByAttValue("class", "article-headline", true, false);
		TagNode body = node.findElementByAttValue("class", "article-bodytext", true, false);


		title.setText(header.findElementByAttValue("class", "title", false, false).getText()  + "");
		subtitle.setText(header.findElementByAttValue("class", "subtitle", false, false).getText() + "");
		byline.setText(replace(header.findElementByAttValue("class", "byline", false, false).getText() + "","&#149;", "\n"));



		TagNode[] fullArticle = body.getElementsByName("p", true);

		article.setText(parseArticle(fullArticle));
	}

	static String replace(String str, String pattern, String replace) {
		int s = 0;
		int e = 0;
		StringBuffer result = new StringBuffer();

		while ((e = str.indexOf(pattern, s)) >= 0) {
			result.append(str.substring(s, e));
			result.append(replace);
			s = e+pattern.length();
		}
		result.append(str.substring(s));
		return result.toString();
	}

	private String parseArticle(TagNode[] source){
		String s = "";

		int length = source.length;
		for(int i = 0; i < length; i++)
			s += source[i].getText() + "\n\n";

		return s;
	}

}
